package com.led.datas;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.led.datatype.ServletResult;

/**
 * Servlet implementation class GetDatas
 */
public class DataServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public DataServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	//
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
//		String token=request.getParameter("token");
//		String dataId = request.getParameter("dataId");
		ServletResult returnResouce = null;

		String opType = request.getParameter("opType");
		if("insert".equalsIgnoreCase(opType)){
			String datas = request.getParameter("jsData");
			boolean ret = DataAccess.saveToDB(datas);
			if(ret){
				returnResouce = new ServletResult("update to Server succes!");
			} else {
				returnResouce = new ServletResult(-1, "update to Server failed!");
			}
//		} else if("get".equals(opType)){
		} else if("getBasic".equalsIgnoreCase(opType)){
			String datas = DataAccess.getDatasBasic();
			returnResouce = new ServletResult(datas);

		} else if("getReal".equalsIgnoreCase(opType)){
			String str_idxReal = request.getParameter("id");
			if(null == str_idxReal || str_idxReal.length() == 0){
				returnResouce = new ServletResult(-1, "no id set for getReal!");
			} else {
				try{
					int id = Integer.parseInt(str_idxReal);
					String datas = DataAccess.getDatasReal(id);
					returnResouce = new ServletResult(datas);
				} catch(Exception e) {
					returnResouce = new ServletResult(-1, "err datas for getReal,id:" + str_idxReal + ")");
				}
			}
		} else {
			String datas = DataAccess.getAllDatas();
			returnResouce = new ServletResult(datas);
		}

		if(null != returnResouce){
			PrintWriter pw = response.getWriter();
			pw.write(returnResouce.toString());
			pw.flush();
			pw.close();
		}
	}

}
